const session = require('../service/session');
const cookie = require('cookie');
const config = require('../config/config');
const micromatch = require('micromatch');

const authKey = '_bundle_token';
const expireTime = 60 * 60 * 24 * 7;

/**
 * 鉴权
 * 除了login接口，其他的接口都需要cookie
 * @param {*} ctx 
 * @param {*} next 
 */
async function auth(ctx, next) {
    const {request, response, db} = ctx;

    // ctx.set('Access-Control-Allow-Methods', '*');
    // ctx.set('Access-Control-Allow-Credentials', 'true');
    // ctx.set('Access-Control-Allow-Headers', '*');
    // ctx.set('Access-Control-Allow-Origin', 'http://localhost:9000');

   // close auth
   if(!config.server.auth) return await next();
    
   const {url, header} = request;

   const allow = micromatch([url], config.server.whitelists);

//    console.log(allow);

   if(allow.length > 0) {
     return await next();
   }

   //token
   const cookieStr = request.header['cookie'];

   if(!cookieStr) {
       return ctx.status = 401;
   }

   const cookieData = cookie.parse(cookieStr);
   const key = cookieData[authKey];

   if(session.exist(key)){
       ctx.currentUser = session.get(key);
       return await next();
   }
   
   return ctx.status = 401;
}

class AuthToken {
    constructor(value){
        this.name = authKey;
        this.key = 'auth_' + getRandomInt(100000);
        this.value = value;
    }

    setStorage(){
        session.add(this.key, this.value);
    }
}

function getRandomInt(max) {
    return Math.floor(Math.random() * max);
}


module.exports = {
    AuthToken,
    auth
}